﻿using Shell32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Server
{
	public partial class Form4 : Form
	{
		string dirPath;
		List<string> files=new List<string> ();
		dataTools data = new dataTools(configClass.databaseip, configClass.databaseusername, "music", configClass.databaseport, configClass.psw);

		public Form4(string _dirPat)
		{
			dirPath = _dirPat;
			InitializeComponent();
		}

		private void button1_Click(object sender, EventArgs e)
		{
			OpenFileDialog dialog;
			Thread t = new Thread((ThreadStart)(() =>
			{

				dialog = new OpenFileDialog();
				dialog.Multiselect = true;//该值确定是否可以选择多个文件
				dialog.Title = "请选择文件夹";
				dialog.Filter = "MP3文件(*.mp3)|*.mp3";
				if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
				{
					foreach (var item in dialog.FileNames)
					{
						files.Add(item);
					}
					
				}

			}));
			t.SetApartmentState(ApartmentState.STA);
			t.Start();
			t.Join();

				button4.Enabled = files.Count>1;
			button2.Enabled = files.Count > 0;
			foreach (var item in files)
			{

				FileInfo file = new FileInfo(item);
				if (listBox1.Items.IndexOf(file.FullName) == -1)
				{ 
				listBox1.Items.Add(file.FullName);
				}
			}
		}

		private void Form4_Load(object sender, EventArgs e)
		{


		}
		string[] getMusicInf(string path)
		{
			string[] Info = new string[7];
			ShellClass sh = new ShellClass();


			Folder dir = sh.NameSpace(Path.GetDirectoryName(path));
			FolderItem item = dir.ParseName(Path.GetFileName(path));
			Info[0] = dir.GetDetailsOf(item, 21);//歌曲名
			Info[1] = dir.GetDetailsOf(item, 13);//作者
			Info[2] = dir.GetDetailsOf(item, 14);//专辑
			Info[3] = dir.GetDetailsOf(item, 27);//时长
			Info[4] = dir.GetDetailsOf(item, 1);//大小
			return Info;
			/*
			//Info[1] = dir.GetDetailsOf(item, 20);
			Info[6] = dir.GetDetailsOf(item, 13);
			Info[3] = dir.GetDetailsOf(item, 27);
			Info[3] = Info[3].Substring(Info[3].IndexOf(":") + 1);
			Info[4] = dir.GetDetailsOf(item, 1);*/
			/*
			 * ID  => DETAIL-NAME
      0   => Name     //文件名
      1   => Size     //文件大小
      13  => Artists   //艺术家
      14  => Album     //专辑
      15  => Year      //出版年份
      20  => Authors   //同艺术家
      21  => Title     //标题
      26  => #         //编号
      27  => Length    //时长
			 */
		}
		private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
		{

			button4.Enabled = listBox1.Items.Count > 1;
			if (listBox1.SelectedItems.Count == 1)
			{
				button5.Enabled = true;
				button6.Enabled = true;
				button2.Enabled = true;
				button7.Enabled = false;
				var file = listBox1.SelectedItem.ToString();
				var inf = getMusicInf(file);
				textBox1.Text = file;
				textBox2.Text = inf[0];
				textBox3.Text = inf[1];
				textBox4.Text = inf[2];
				textBox5.Text = inf[3];
				textBox6.Text = inf[4];
				textBox7.Text = GetMD5HashFromFile(file);
			}
			else if (listBox1.SelectedItems.Count > 1)
			{

				button5.Enabled = true;
				button6.Enabled = false;
				button2.Enabled = true;
				button7.Enabled = true;
			}
			else 
			{
				button2.Enabled = false;
				button5.Enabled = false;
				button6.Enabled = false;

				button7.Enabled = false;
			}
		}
		public string GetMD5HashFromFile(string fileName)
		{
			try
			{
				FileStream file = new FileStream(fileName, System.IO.FileMode.Open);
				MD5 md5 = new MD5CryptoServiceProvider();
				byte[] retVal = md5.ComputeHash(file);
				file.Close();
				StringBuilder sb = new StringBuilder();
				for (int i = 0; i < retVal.Length; i++)
				{
					sb.Append(retVal[i].ToString("x2"));
				}
				return sb.ToString();
			}
			catch (Exception ex)
			{
				throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
			}
		}
		

		private void button4_Click(object sender, EventArgs e)
		{
			if (button4.Text == "多选")
			{
				listBox1.SelectionMode = SelectionMode.MultiExtended;

				button4.Text = "取消多选";
			}
			else
			{

				button7.Enabled = false;
				button6.Enabled = true;
				listBox1.SelectionMode = SelectionMode.One;
				button4.Text = "多选";
			}
		}

		private void button5_Click(object sender, EventArgs e)
		{
			if (listBox1.SelectedItems.Count > 0)
			{
				for (int i = this.listBox1.Items.Count - 1; i >= 0; i--)
				{
					this.listBox1.Items.Remove(this.listBox1.SelectedItem);
				}
			}
		}

		private void button6_Click(object sender, EventArgs e)
		{
			if (listBox1.SelectedItems.Count == 1)
			{
				string type = textBox1.Text.Split('.')[textBox1.Text.Split('.').Length - 1];
				if (data.tableExit("V1"))
				{
					if (!checkMD5(textBox7.Text))
					{
						String newpath = dirPath;//新目录
						String oldfile = textBox1.Text;//文件当前文件名
						String newfiles = textBox7.Text;//新文件名

						removefile(newfiles, oldfile, newpath, type);
						data.insert("V1", new string[] { "title", "artists", "album", "length", "size", "mid", "up", "date", "type" },
							new string[] { textBox2.Text, textBox3.Text, textBox4.Text, textBox5.Text, textBox6.Text, textBox7.Text, textBox8.Text, DateTime.Now.ToString(), type });




						MessageBox.Show("上传成功！");
					}
					else
					{
						MessageBox.Show("此歌曲已在数据库中");
					}
				}
				else
				{
					String newpath = dirPath;//新目录
					String oldfile = textBox1.Text;//文件当前文件名
					String newfiles = textBox7.Text;//新文件名

					removefile(newfiles, oldfile, newpath, type);
					data.insert("V1", new string[] { "title", "artists", "album", "length", "size", "mid", "up", "date", "type" },
						new string[] { textBox2.Text, textBox3.Text, textBox4.Text, textBox5.Text, textBox6.Text, textBox7.Text, textBox8.Text, DateTime.Now.ToString(), type });




					MessageBox.Show("上传成功！");
				}


			}
		}
		public static void removefile(String newfiles, String oldAllfiles, String newpath, string type)
		{

			FileInfo oldfile = new FileInfo(oldAllfiles);
			if (oldfile.Exists)
			{
				oldfile.CopyTo(newpath + "/" + newfiles + "." + type);

			}
			else
				Console.WriteLine("文件不存在！");

		}
		bool checkMD5(string md5)
		{
			var I = data.searchListCount("V1", new string[] { "mid" }, new string[] { md5 }).msg;
			if (!data.tableExit("V1"))
				return false;
			if ((int)data.searchListCount("V1", new string[] { "mid" }, new string[] { md5 }).msg > 0)
				return true;
			return false;
		}
		bool update(string path)
		{

			string md5 = GetMD5HashFromFile(path);
			if (checkMD5(md5))
			{

				MessageBox.Show("歌曲“" + path + "”已在数据库中");
				return false;
			}
			string type = path.Split('.')[path.Split('.').Length - 1];
			var inf = getMusicInf(path);
			string title = inf[0];
			string artists = inf[1];
			string album = inf[2];
			string length = inf[3];
			string size = inf[4];
			String newpath = dirPath;//新目录
			String oldfile = path;//文件当前文件名

			FileInfo file = new FileInfo(path);
			String newfiles = md5;//新文件名(无后缀名)

			removefile(newfiles, oldfile, newpath, type);
			data.insert("V1", new string[] { "title", "artists", "album", "length", "size", "mid", "up", "date", "type" },
				new string[] { title, artists, album, length, size, md5, textBox8.Text, DateTime.Now.ToString(), type });


			return true;
		}


		private void button7_Click(object sender, EventArgs e)
		{
			int a = listBox1.SelectedItems.Count;
			int b = 0;
			List<string> succeed = new List<string>();
			List<string> error = new List<string>();
			foreach (var item in listBox1.SelectedItems)
			{
				string path = item.ToString();
				if (update(path))
				{
					succeed.Add(path);
					b++;
				}
				else 
				{
					error.Add(path);
				}

			}

			string str = "尝试上传了 " + a + " 项，成功了 " + b + " 项\r\n";
			if (a > b)
			{
				foreach (var item in error)
				{
					str += item + " ";
				}
				str += "未完成";
			}
				foreach (var item in succeed)
				{
					listBox1.Items.Remove(item);
				}
			

			MessageBox.Show(str);
		}

		private void button2_Click(object sender, EventArgs e)
		{
			if (listBox1.Items.Count > 0)
			{
				int a = listBox1.Items.Count;
				int b = 0;
				List<string> succeed = new List<string>();
				List<string> error = new List<string>();
				foreach (var item in listBox1.Items)
				{
					string path = item.ToString();
					if (update(path))
					{
						succeed.Add(path);
						b++;
					}
					else
					{
						error.Add(path);
					}

				}

				string str = "尝试上传了 " + a + " 项，成功了 " + b + " 项\r\n";
				if (a > b)
				{
					foreach (var item in error)
					{
						str += item + " ";
					}
					str += "未完成";
				}
				foreach (var item in succeed)
				{
					listBox1.Items.Remove(item);
				}


				MessageBox.Show(str);
			}
		}
	}
	}
